package com.atguigu.study.service;

import com.fasterxml.jackson.databind.JsonNode;
import jakarta.annotation.Resource;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @auther zzyy
 * @create 2025-03-12 23:24
 */
@Service
public class WeatherService {

    //和风天气开发服务 https://dev.qweather.com/
    private static final String API_KEY = "2406fff403ae4202988d4fa244e04f67"; // 替换成你自己的和风天气API密钥
    private static final String BASE_URL = "https://devapi.qweather.com/v7/weather/now?location=%s&key=%s";

    public JsonNode getWeatherV2(String city) throws Exception {
        String url = String.format(BASE_URL, city, API_KEY);
        // 使用默认配置创建HttpClient实例
        var httpClient = HttpClients.createDefault();

        // 创建请求工厂并将其设置给RestTemplate
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient);
        String response = new RestTemplate(factory).getForObject(url, String.class);

        // 解析JSON响应
        JsonNode jsonNode = new ObjectMapper().readTree(response);
        return jsonNode;
    }

}
